package cn.doitedu.rules.dao;

import cn.doitedu.date.gen.LogBean;
import cn.doitedu.rules.pojo.EventParam;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
public class UserHistoryEventClickHouseDaoImpl implements UserHistoryEventDao {

    public Connection connection;

    public UserHistoryEventClickHouseDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public boolean isMatchCount(LogBean event, List<EventParam> userActionCountConditions) throws Exception {
        if (userActionCountConditions != null && userActionCountConditions.size() > 0) {
            for (EventParam eventParam : userActionCountConditions) {
                String sql = eventParam.getSql();
                Map<String, String> properties = eventParam.getProperties();
                Set<Map.Entry<String, String>> entries = properties.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    sql += " and properties['" + key + "'] = " + "'" + value + "'";
                }
                log.debug("===========> 查询clickhouse的SQL为：{}", sql);

                PreparedStatement pstm = connection.prepareStatement(sql);
                pstm.setString(1, event.getDeviceId());
                pstm.setString(2, event.getEventId());
                pstm.setLong(3, eventParam.getStartTime());
                pstm.setLong(4, eventParam.getEndTime());
                ResultSet resultSet = pstm.executeQuery();
                if (resultSet.next()) {
                    long historyCount = resultSet.getLong(1);
                    if (historyCount < eventParam.getThreshCount()) {
                        return false;
                    }
                }
                resultSet.close();
                pstm.close();

            }
            return true;
        } else {
            return true;
        }

    }
    @Override

    public boolean isMatchSequence(LogBean event, List<EventParam> userActionSequenceCondition) throws Exception{



        if (userActionSequenceCondition != null && userActionSequenceCondition.size() > 0) {



            EventParam eventParam = userActionSequenceCondition.get(0);



            String sql = eventParam.getSql();



            PreparedStatement pstm = connection.prepareStatement(sql);

            pstm.setString(1, event.getDeviceId());



            ResultSet resultSet = pstm.executeQuery();



            if (resultSet.next()) {

                int isOne = resultSet.getInt(1);

                if (isOne != 1) {

                    return false;

                }

            }

        }

        return true;

    }


}
